<!-- src/components/CarMarker.vue -->
<template>
  <div></div>
</template>

<script>
export default {
  name: 'CarMarker',
  props: {
    map: {
      type: Object,
      required: true
    },
    item: {
      type: Array,
      required: true
    },
    itemIndex: {
      type: String,
      required: ''
    },
    carWindow: {
      type: Object,
      required: true
    },
    carWindowContent: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      carMarker: null,
      passedPolyline: null,
      currentIndex: 0,
      passedPath: [],
      routeInfo: [],
      moveInterval: null, // 定时器引用
      moveSpeed: 50, // 控制行驶速度的变量，单位毫秒
    }
  },
  watch: {
    item: {
      handler(value) {
        // 安全检查：确保数组不为空
        if (value && Array.isArray(value) && value.length > 0) {
          // 更新 routeInfo
          this.routeInfo = value;
          this.currentIndex = this.currentIndex === 0 ? 0 : this.currentIndex - 1; // 保持当前位置不变，除非是初始状态
          this.startMoving()
        }
      },
      deep: true // 深度监听数组内对象属性的变化
    }
  },
  created() {
    // 在 created 钩子中初始化 routeInfo，此时 props 已经初始化
    this.routeInfo = this.item || [];
  },
  mounted() {
    this.initCarMarker()
  },
  methods: {
    initCarMarker() {
      // 确保routeInfo有数据
      if (!this.routeInfo || this.routeInfo.length === 0) {
        return;
      }

      // 创建小汽车marker
      this.carMarker = new AMap.Marker({
        map: this.map,
        position: [this.routeInfo[0].longitude, this.routeInfo[0].latitude],
        icon: new AMap.Icon({
          size: new AMap.Size(36, 36),
          image: require('@/assets/images/car-icon.png'), // 使用require引入本地图片
          imageSize: new AMap.Size(36, 36)
        }),
        offset: new AMap.Pixel(-18, -18),
        angle: 0, // 初始角度
        autoRotation: false // 关闭自动旋转，我们手动控制
      });

      // 创建已行驶轨迹线
          this.passedPath.push([this.routeInfo[0].longitude, this.routeInfo[0].latitude]);
          const colorArr = ['#007BFF', '#ffc107', '#f44336', '#66bb6a']
          const colorStr = this.itemIndex == 'G1001'? '#007BFF' : this.itemIndex == 'G0801'?'#ffc107':'#66bb6a';
      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        path: this.passedPath,
        strokeColor: colorStr, // 科技蓝
        strokeOpacity: 0.8,
        strokeWeight: 6,
        strokeStyle: "solid",
        isOutline: true,
        outlineColor: "#ffffff",
        borderWeight: 1
      });

      // 打开信息框并保持显示
      this.updateInfoWindow();
      if (this.map && this.carMarker && this.routeInfo && this.routeInfo.length > 0 && this.carWindowContent === this.routeInfo[0].trainNo) {
        this.carWindow.open(this.map, this.carMarker.getPosition());
      }

      // 启动车辆移动定时器
      this.startMoving();

      // 监听地图移动事件，确保车辆信息窗口始终显示在正确位置
      if (this.carMarker) {
        this.carMarker.on('moving', () => {
          if (this.carWindow && this.carMarker && this.routeInfo && this.routeInfo.length > 0 && this.carWindowContent === this.routeInfo[0].trainNo) {
            this.carWindow.setPosition(this.carMarker.getPosition());
          }
        });

        // 绑定车辆标记点击事件，确保点击时显示信息窗口
        this.carMarker.on('click', () => {
          if (this.map && this.carMarker && this.routeInfo && this.routeInfo.length > 0) {
            // 更新父组件的carWindowContent
            const trainNo = this.routeInfo[0].trainNo;
            this.$emit('updateCarWindow', trainNo);
            this.carWindow.open(this.map, this.carMarker.getPosition());
            setTimeout(() => {
              this.updateInfoWindow(this.routeInfo[0]);
            }, 30)
          }
        });
      }
    },

    // 开始移动车辆
    startMoving() {
      if (this.moveInterval) {
        clearInterval(this.moveInterval);
      }

      this.moveInterval = setInterval(() => {
        const isFinished = this.moveToNextPoint();
        if (isFinished) {
          clearInterval(this.moveInterval);
          this.moveInterval = null;
        }
      }, this.moveSpeed); // 使用moveSpeed变量控制速度
    },

    // 修改移动速度的方法
    changeMoveSpeed(newSpeed) {
      this.moveSpeed = newSpeed;
      if (this.moveInterval) {
        this.startMoving(); // 重新启动定时器以应用新速度
      }
    },

    moveToNextPoint() {
      // 确保routeInfo存在且有数据
      if (!this.routeInfo || this.routeInfo.length === 0) {
        return true; // 表示已到达终点
      }

      // 保存当前索引
      const prevIndex = this.currentIndex;

      // 增加索引
      this.currentIndex++;

      if (this.item[0].trainNo === this.carWindowContent) {
        // console.log('移动到下一个点，当前索引：', this.routeInfo.length, this.currentIndex);
      }

      // 如果已经到达最后一个点，则停止定时器
      if (this.currentIndex >= this.routeInfo.length) {
        return true; // 表示已到达终点
      }

      const currentPoint = this.routeInfo[this.currentIndex];
      const position = [currentPoint.longitude, currentPoint.latitude];

      // 计算车辆朝向角度
      let angle = 0;
      if (prevIndex < this.routeInfo.length - 1) {
        const prevPoint = this.routeInfo[prevIndex];
        const nextPoint = this.routeInfo[this.currentIndex];
        angle = this.calculateAngle(
          prevPoint.longitude, prevPoint.latitude,
          nextPoint.longitude, nextPoint.latitude
        );
      }

      // 更新车辆标记位置和角度
      if (this.carMarker) {
        this.carMarker.setPosition(position);
        this.carMarker.setAngle(angle); // 设置车辆朝向
      }

      // 更新已行驶轨迹
      this.passedPath.push(position);
      if (this.passedPolyline) {
        this.passedPolyline.setPath(this.passedPath);
      }

      // 更新信息窗口内容和位置
      this.updateInfoWindow();
      if (this.carWindow && this.carMarker && this.routeInfo && this.routeInfo.length > 0 && this.carWindowContent === this.routeInfo[0].trainNo) {
        this.carWindow.setPosition(position); // 确保信息窗口跟随车辆移动
      }

      return false; // 表示未到达终点
    },

    // 计算两点之间的角度

        calculateAngle(prevLng, prevLat, nextLng, nextLat) {
        // 将经纬度差转换为平面坐标差
        const dx = nextLng - prevLng;
        const dy = nextLat - prevLat;

        // 计算角度（弧度转角度）
        // 注意：高德地图中，y轴向上为正，x轴向右为正
        // Math.atan2(dy, dx) 返回的是从正x轴到点(dx,dy)的弧度
        let angle = Math.atan2(dy, dx) * 180 / Math.PI;

        // 调整角度，使正北为0度，顺时针为正方向
        // 高德地图中车辆图标通常需要这样的调整
        angle = 90 - angle;

        // 确保角度在0-360范围内
        if (angle < 0) {
            angle += 360;
        }
        if (angle >= 360) {
            angle -= 360;
        }

        return angle;
        },

    updateInfoWindow(data) {
      if (this.carWindowContent !== this.routeInfo[0].trainNo) {
        return
      }
      if (!data) {
        // 确保routeInfo存在且currentIndex有效
        if (!this.routeInfo || this.routeInfo.length === 0 || this.currentIndex >= this.routeInfo.length || this.currentIndex < 0) {
          return;
        }
      }

      const currentPoint = data || this.routeInfo[this.currentIndex];
      const trainNo = this.routeInfo && this.routeInfo.length > 0 ? this.routeInfo[0].trainNo : 'unknown';
      // console.log('当前：', trainNo, currentPoint)

      // 额外检查currentPoint是否存在
      if (!currentPoint) {
        return;
      }

      const content = `
        <div class="tech-car-info-container">
          <div class="tech-car-info-header">
            <div class="header-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M5 12H19" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 5L19 12L12 19" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="header-text">${currentPoint.trainNo || '未知车辆'}(${currentPoint.workNo || '暂无任务'})</div>
          </div>
          <div class="tech-car-info-body">
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="#4fc3f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  线路
                </div>
                <div class="info-value">${currentPoint.lineName || '8号线'}</div>
              </div>

              <div class="info-item">
                <div class="info-label">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M5.5 5.5L18.5 18.5M18.5 5.5L5.5 18.5" stroke="#4fc3f7" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                  速度
                </div>
                <div class="info-value speed-value">${currentPoint.speed ? currentPoint.speed.toFixed(2) : '0.00'} <span class="unit">KM/h</span></div>
              </div>
            </div>

          </div>

        </div>
      `;

      if (this.carWindow && this.routeInfo && this.routeInfo.length > 0 && this.carWindowContent === this.routeInfo[0].trainNo) {
        this.carWindow.setContent(content);
      }
    },

    getCurrentIndex() {
      return this.currentIndex;
    }
  },
  beforeDestroy() {
    // 清理定时器
    if (this.moveInterval) {
      clearInterval(this.moveInterval);
    }

    // 清理车辆标记
    if (this.carMarker) {
      this.carMarker.setMap(null);
    }

    // 清理信息窗口
    if (this.carWindow) {
      this.carWindow.close();
    }

    // 清理轨迹线
    if (this.passedPolyline) {
      this.passedPolyline.setMap(null);
    }
  }
}
</script>

<style>
/* 科技感车辆信息弹窗样式 */
.tech-car-info-container {
  background: linear-gradient(145deg, #0c1e3e, #1a3a6a);
  border-radius: 12px;
  box-shadow:
    0 15px 35px rgba(0, 0, 0, 0.5),
    0 0 25px rgba(33, 150, 243, 0.4),
    inset 0 0 20px rgba(33, 150, 243, 0.3);
  border: 1px solid rgba(79, 195, 247, 0.6);
  overflow: hidden;
  min-width: 320px;
  transform-style: preserve-3d;
  position: relative;
}

.tech-car-info-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4fc3f7, transparent);
}

.tech-car-info-header {
  background: linear-gradient(90deg, #0277bd, #0288d1);
  color: white;
  padding: 5px 16px;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  position: relative;
  overflow: hidden;

}

.tech-car-info-header::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.tech-car-info-header:hover::after {
  left: 100%;
}

.header-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.header-text {
  letter-spacing: 1px;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.5);
}

.tech-car-info-body {
  padding: 2px 2px 0 2px;

}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.info-item {
  background: linear-gradient(145deg, rgba(2, 119, 189, 0.2), rgba(2, 136, 209, 0.1));
  border-radius: 10px;
  padding: 9px;
  border: 1px solid rgba(79, 195, 247, 0.3);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.info-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #4fc3f7, transparent);
}

.info-item:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4), 0 0 20px rgba(33, 150, 243, 0.5);
  border-color: rgba(79, 195, 247, 0.7);
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #4fc3f7;
  font-size: 13px;
  margin-bottom: 10px;
}

.info-value {
  color: #e3f2fd;
  font-size: 17px;
  font-weight: 700;
  text-shadow: 0 0 10px rgba(79, 195, 247, 0.6);
}

.speed-value {
  color: #4fc3f7;
  font-size: 20px;
}

.unit {
  font-size: 13px;
  color: #bbdefb;
}

.tech-progress-bar {
  margin-top: 18px;
}

.progress-label {
  color: #bbdefb;
  font-size: 14px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-track {
  height: 10px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  overflow: hidden;
  box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(79, 195, 247, 0.2);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #0277bd, #4fc3f7);
  border-radius: 5px;
  box-shadow: 0 0 12px rgba(79, 195, 247, 0.8);
  transition: width 0.5s ease;
  position: relative;
}

.progress-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: progressGlow 2s infinite;
}

@keyframes progressGlow {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.tech-car-info-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 22px;
  background: rgba(0, 25, 50, 0.7);
  border-top: 1px solid rgba(79, 195, 247, 0.3);
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #bbdefb;
  font-size: 15px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #9e9e9e;
  box-shadow: 0 0 6px #9e9e9e;
}

.status-dot.online {
  background: #4caf50;
  box-shadow: 0 0 10px #4caf50;
}

.timestamp {
  color: #90caf9;
  font-size: 13px;
  font-weight: 500;
}

/* 弹窗动画效果 */
.amap-info-content {
  background: transparent !important;
  padding: 0 !important;
  max-width: none !important;
  border: none !important;
  box-shadow: none !important;
}

.amap-info-sharp {
  transform: perspective(1000px) rotateX(5deg);
  transition: transform 0.3s ease;
  animation: popup 0.4s ease-out;
}

.amap-info-sharp:hover {
  transform: perspective(1000px) rotateX(0deg);
}

@keyframes popup {
  0% {
    opacity: 0;
    transform: scale(0.8) translateY(20px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .tech-car-info-container {
    min-width: 280px;
  }
}
</style>
